package com.graduate.service.impl;

import java.util.List;
import java.util.Map;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.graduate.mapper.SysRoleMapper;
import com.graduate.model.SysRole;
import com.graduate.service.ISysRoleService;
import com.graduate.util.PageInfo;

@Service("roleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService{
	@Autowired
	private SysRoleMapper roleMapper;
	public PageInfo getPageInfo(PageInfo pageInfo) {
		Page<Map<String, Object>> page = new Page<Map<String, Object>>(pageInfo.getNowpage(), pageInfo.getPagesize());
		List<Map<String, Object>> list = roleMapper.getPageInfo(page, pageInfo.getCondition());
		pageInfo.setRows(list);
		pageInfo.setTotal(page.getTotal());
		return pageInfo;
	}

	@Override
	public SysRole selectRole(Map<String, Object> map) {
		return roleMapper.selectRole(map);	
	}

	@Override
	@Transactional(isolation=Isolation.DEFAULT)
	public Integer saveRole(SysRole role) {
		Integer result =roleMapper.insert(role); //插入新增用户表
		if(!CollectionUtils.isEmpty(role.getRoleAndMenuList())){
			result+=roleMapper.saveBatchRoleAndMenu(role);//批量插入角色和菜单关系表
		}
		return result;
	}

	@Override
	@Transactional(isolation=Isolation.DEFAULT)
	public Integer updateRole(SysRole role) {
		//执行更新角色表根据id更新角色
		Integer result =roleMapper.updateById(role); 
		//删除中间表角色关联关系。
		result+=roleMapper.deleteBatchroleAndMenuByRoleId(role.getId());
		//添加中间表关联关系。
		result+=roleMapper.saveBatchRoleAndMenu(role);//批量插入角色和菜单关系表
		return result;
	}

	@Override
	@Transactional(isolation=Isolation.DEFAULT)
	public Integer deleteRole(String id) {
		//先通过id查询到这个角色，
		Integer result = roleMapper.deleteById(id);
		//删除角色和菜单中间表数据，
		result += roleMapper.deleteBatchroleAndMenuByRoleId(id);
		//删除角色和用户中间表数据
		result += roleMapper.deleteBatchroleAndUserByRoleId(id);
		return result;
	}

	@Override
	@Transactional(isolation=Isolation.DEFAULT)
	public Integer saveRoleAndUser(SysRole role) {
		Integer result = roleMapper.deleteRoleAndUser(role);
		result=roleMapper.saveRoleAndUser(role);
		return result;
		
	}

	@Override
	public PageInfo getPageInfoRoleGrantUser(PageInfo pageInfo) {
		Page<Map<String, Object>> page = new Page<Map<String, Object>>(pageInfo.getNowpage(), pageInfo.getPagesize());
		List<Map<String, Object>> list = roleMapper.getPageInfoRoleGrantUser(page, pageInfo.getCondition());
		pageInfo.setRows(list);
		pageInfo.setTotal(page.getTotal());
		return pageInfo;
	}

	@Override
	public List<SysRole> getRoleList(SysRole role) {
		return roleMapper.getRoleList(role);
	}
}
